package com.util;

import android.annotation.SuppressLint;
import android.os.Environment;
import android.util.Log;
import android.util.Xml;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xmlpull.v1.XmlSerializer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;


/**
 * 读写配置文件类
 *
 * @author 刘亚东
 */
@SuppressLint("SdCardPath")
public class AnalysisConfiguration {
    public static String SCJConfigPath = Environment.getExternalStorageDirectory() + "/scj";
    private static DocumentBuilderFactory dbc = DocumentBuilderFactory
            .newInstance();

    private static DocumentBuilder db = null;

    private static Document doc = null;

    private static Element eml = null;

    private static NodeList list = null;

    private static String index = "/config/";

    /**
     * 删除配置文件
     *
     * @param fileName
     */
    public static void deleteConfig(String fileName) {
        File file = new File(SCJConfigPath + index + fileName);
        if (file.exists()) {
            file.delete();
        }
    }
    /**
     * 读取设备通信配置文件
     *
     *
     */
    public static Map<String, String> readConfig(String fileName) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            db = dbc.newDocumentBuilder();
            // 配置XML文件
            File folder = new File( SCJConfigPath + index);
            if (!folder.exists()) {
                //folder.delete();
                folder.mkdirs();
            }
            File file = new File( SCJConfigPath + index + fileName);
            if (!file.exists()) {
                AnalysisConfiguration.WriteXmlStr(fileName, map);
                return  map;
            }
            doc = db.parse(file);
            eml = doc.getDocumentElement();
            list = eml.getChildNodes();
            for (int i = 0; i < list.getLength(); i++) {
                Node node = list.item(i);
                if (node.getNodeType() != Node.TEXT_NODE
                        && node.getNodeType() != Node.COMMENT_NODE) {
                    NodeList li = node.getChildNodes();
                    for (int j = 0; j < li.getLength(); j++) {
                        Node no = li.item(j);
                        if (no.getNodeType() != Node.TEXT_NODE
                                && no.getNodeType() != Node.COMMENT_NODE) {
                            map.put(no.getNodeName(), no.getFirstChild()
                                    .getNodeValue());
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
    /**
     * 读取设备通信配置文件
     *
     * @param
     */
    public static Map<String, String> readConfig(String fileName, Map<String, String> codemaps) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            db = dbc.newDocumentBuilder();
            // 配置XML文件
            File folder = new File(SCJConfigPath + index);
            if (!folder.exists()) {
                //folder.delete();
                folder.mkdirs();
            }
            File file = new File(SCJConfigPath + index + fileName);
            if (!file.exists()) {
                AnalysisConfiguration.WriteXmlStr(fileName, codemaps);
                return codemaps;
            }
            doc = db.parse(file);
            eml = doc.getDocumentElement();
            list = eml.getChildNodes();
            for (int i = 0; i < list.getLength(); i++) {
                Node node = list.item(i);
                if (node.getNodeType() != Node.TEXT_NODE
                        && node.getNodeType() != Node.COMMENT_NODE) {
                    NodeList li = node.getChildNodes();
                    for (int j = 0; j < li.getLength(); j++) {
                        Node no = li.item(j);
                        if (no.getNodeType() != Node.TEXT_NODE
                                && no.getNodeType() != Node.COMMENT_NODE) {
                            map.put(no.getNodeName(), no.getFirstChild()
                                    .getNodeValue());
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public static String SCJConfiguration = "SCJConfiguration.xml";

    /**
     * 生成XML字符串格式
     *
     * @param fileName
     * @param map
     */
    public static boolean WriteXmlStr(String fileName, Map<String, String> map) {
        XmlSerializer serializer = Xml.newSerializer();
        StringWriter writer = new StringWriter();
        try {
            if (fileName.equals(SCJConfiguration)) {
                serializer.setOutput(writer);
                serializer.startDocument("UTF-8", true);
                serializer.startTag("", "scj");

                serializer.startTag("", "connection");

                serializer.startTag("", "address");
                serializer.text(map.get("address"));
                serializer.endTag("", "address");

                serializer.startTag("", "port");
                serializer.text(map.get("port"));
                serializer.endTag("", "port");

                serializer.startTag("", "url");
                serializer.text(map.get("url"));
                serializer.endTag("", "url");

                serializer.endTag("", "connection");

                serializer.startTag("", "connection");

                serializer.startTag("", "TxChannel");
                serializer.text(map.get("TxChannel"));
                serializer.endTag("", "TxChannel");

                serializer.startTag("", "RxChannel");
                serializer.text(map.get("RxChannel"));
                serializer.endTag("", "RxChannel");

                serializer.startTag("", "TxPower");
                serializer.text(map.get("TxPower"));
                serializer.endTag("", "TxPower");

                serializer.startTag("", "RxPower");
                serializer.text(map.get("RxPower"));
                serializer.endTag("", "RxPower");

                serializer.startTag("", "CRC");
                serializer.text(map.get("CRC"));
                serializer.endTag("", "CRC");

                serializer.startTag("", "PsamNumForVersion1");
                serializer.text(map.get("PsamNumForVersion1"));
                serializer.endTag("", "PsamNumForVersion1");

                serializer.startTag("", "PsamNumForVersion2");
                serializer.text(map.get("PsamNumForVersion2"));
                serializer.endTag("", "PsamNumForVersion2");

                serializer.startTag("", "PsamNumForVersion3");
                serializer.text(map.get("PsamNumForVersion3"));
                serializer.endTag("", "PsamNumForVersion3");

                serializer.startTag("", "PsamNumForVersion4");
                serializer.text(map.get("PsamNumForVersion4"));
                serializer.endTag("", "PsamNumForVersion4");

                serializer.startTag("", "BstNumber");
                serializer.text(map.get("BstNumber"));
                serializer.endTag("", "BstNumber");

                serializer.startTag("", "BstInterval");
                serializer.text(map.get("BstInterval"));
                serializer.endTag("", "BstInterval");

                serializer.startTag("", "TrasferChannelNumber");
                serializer.text(map.get("TrasferChannelNumber"));
                serializer.endTag("", "TrasferChannelNumber");

                serializer.startTag("", "TrasferChannelInterval");
                serializer.text(map.get("TrasferChannelInterval"));
                serializer.endTag("", "TrasferChannelInterval");

                serializer.endTag("", "connection");

                serializer.startTag("", "connection");

                serializer.startTag("", "IsModifySignedDate");
                serializer.text(map.get("IsModifySignedDate"));
                serializer.endTag("", "IsModifySignedDate");

                serializer.startTag("", "SignedDate");
                serializer.text(map.get("SignedDate"));
                serializer.endTag("", "SignedDate");

                serializer.endTag("", "connection");

                serializer.startTag("", "connection");

                serializer.startTag("", "IsModifyExpiredDate");
                serializer.text(map.get("IsModifyExpiredDate"));
                serializer.endTag("", "IsModifyExpiredDate");

                serializer.startTag("", "ExpiredM");
                serializer.text(map.get("ExpiredM"));
                serializer.endTag("", "ExpiredM");

                serializer.startTag("", "ExpiredN");
                serializer.text(map.get("ExpiredN"));
                serializer.endTag("", "ExpiredN");

                serializer.startTag("", "IsExpiredN");
                serializer.text(map.get("IsExpiredN"));
                serializer.endTag("", "IsExpiredN");

                serializer.endTag("", "connection");

                serializer.startTag("", "connection");

                serializer.startTag("", "City");
                serializer.text(map.get("City"));
                serializer.endTag("", "City");

                serializer.startTag("", "PassWord");
                serializer.text(map.get("PassWord"));
                serializer.endTag("", "PassWord");

                serializer.startTag("", "KeyType");
                serializer.text(map.get("KeyType"));
                serializer.endTag("", "KeyType");

                serializer.endTag("", "connection");

                serializer.endTag("", "scj");

                serializer.endDocument();

            }
            return writeFileToSD(writer.toString(), fileName);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 写SD卡数据
     *
     * @param str_xie
     * @param fileName
     * @return
     */
    public static boolean writeFileToSD(String str_xie, String fileName) {
        try {
            String sdStatus = Environment.getExternalStorageState();

            if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
                Log.d("TestFile",
                        "SD card is not avaiable/writeable right now.");
                return false;
            }
            File path = new File(SCJConfigPath + index);
            File file = new File(SCJConfigPath + index + fileName);
            if (!path.exists()) {
                Log.d("TestFile", "Create the path:"
                        + SCJConfigPath);
                path.mkdirs();
            }
            file.createNewFile();
            FileOutputStream stream = new FileOutputStream(file);
            String s = str_xie;
            byte[] buf = s.getBytes();
            stream.write(buf);
            stream.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 比较内容是否一致
     *
     * @param map1
     * @param map2
     * @return false:不一致
     */
    public static boolean compareMap(Map<String, String> map1, Map<String, String> map2) {
        Iterator iter = map1.keySet().iterator();

        boolean equals = true;
        if (map1.size() != map2.size())
            return false;
        while (iter.hasNext()) {
            Object key = iter.next();
            if (!map2.containsKey(key)) {
                equals = false;
                break;
            }
        }
        return equals;
    }
}
